import 'package:fish_redux/fish_redux.dart';
import 'package:flutter/cupertino.dart' hide Action;
import 'package:flutter/material.dart' hide Action;
import 'package:rflutter_alert/rflutter_alert.dart';
import 'package:www.znpigai.teacher/global_store/action.dart';
import 'package:www.znpigai.teacher/global_store/state.dart';
import 'package:www.znpigai.teacher/global_store/store.dart';
import 'package:www.znpigai.teacher/utils/http.dart';
import 'package:www.znpigai.teacher/utils/util.dart';

import 'action.dart';
import 'item/action.dart';
import 'item/state.dart';
import 'state.dart';

Effect<ClassListState> buildEffect() {
  return combineEffects(<Object, Effect<ClassListState>>{
    Lifecycle.initState: _onReload,
    ClassListAction.onLoad: _onLoad,
    ClassListAction.onReload: _onReload,
    ClassListAction.onAdd: _onAdd,
    ClassListAction.onDelete: _onDelete,
  });
}

void _onReload(Action action, Context<ClassListState> ctx) async {
  if (ctx.state.isLoading) {
    return;
  }

  if (action.payload != null) {
    action.payload(); // callback
  }

  _getClass(action, ctx);
}

void _onLoad(Action action, Context<ClassListState> ctx) async {
  var isLoading = ctx.state.isLoading;
  if (isLoading) {
    return;
  }

  _getClass(action, ctx);
}

void _onDelete(Action action, Context<ClassListState> ctx) async {
  bool ok = await Util.showConfirmDialog('删除', '确定要删除？', ctx.context);
  if (!ok) {
    return;
  }

  var code = action.payload;

  ctx.dispatch(ClassActionCreator.loading());
  var result;
  if (GlobalState.isTeacher) {
    result = await Http.get('/correct/teacher/api/class/del.mvc',
        query: {'id': code});
  } else {
    result = await Http.post('/correct/student/api/class/exit.mvc',
        data: {'code': code});
  }
  ctx.dispatch(ClassActionCreator.loaded());

  if (result.success) {
    ctx.dispatch(ClassListActionCreator.deleted(code));
  } else {
    Util.alertFail(result, ctx.context);
  }
}

void _onAdd(Action action, Context<ClassListState> ctx) async {
  Map<String, String> data = {};
  if (GlobalState.isTeacher) {
    data = await _inputClassInfo(ctx);
  } else {
    String code = await Util.showInputDialog(
        '加入班级', '输入班级码加入班级，与小伙伴一起进步', '', '请输入班级码', ctx.context);
    if (code != null) {
      data = {'code': code};
    }
  }

  if (!(data?.isNotEmpty == true)) {
    return;
  }

  ctx.dispatch(ClassListActionCreator.loading());
  var result = await Http.post(
      '/correct/${GlobalState.userRole}/api/class/add.mvc',
      data: data);
  ctx.dispatch(ClassListActionCreator.loaded());

  if (result.success) {
    ctx.dispatch(ClassListActionCreator.onReload(null));
  } else {
    Util.alertFail(result, ctx.context);
  }
}

void _getClass(Action action, Context<ClassListState> ctx) async {
  ctx.dispatch(ClassListActionCreator.loading());

  HttpResult result;
  if (GlobalState.isTeacher) {
    var url = "/correct/${GlobalState.userRole}/api/profile.mvc";
    // 一次拿全所有班级
    result = await Http.get(url,
        query: {'cpage': GlobalState.firstPageIndex, 'psize': 100});
    ctx.dispatch(ClassListActionCreator.loaded());
    if (result.success) {
      GlobalStore.store
          .dispatch(GlobalActionCreator.onChangeUserInfo(result.data));

      var responseList = result.data['classList'];
      List<ClassState> items = new List();
      if (responseList != null) {
        responseList.forEach((item) {
          try {
            ClassState cellData = new ClassState.fromJson(item);
            items.add(cellData);
          } catch (e) {
            // No specified type, handles all
          }
        });
      }

      ctx.dispatch(ClassListActionCreator.listResult(
          items, 100, GlobalState.firstPageIndex));
    } else {
      Util.alertFail(result, ctx.context);
    }
  } else {
    var url = "/correct/student/api/my/class.mvc";
    // 一次拿全所有班级
    result = await Http.get(url);
    ctx.dispatch(ClassListActionCreator.loaded());
    if (result.success) {
      var responseList = result.data;

      List<ClassState> items = new List();
      if (responseList != null) {
        responseList.forEach((item) {
          try {
            ClassState cellData = new ClassState.fromJson(item);
            items.add(cellData);
          } catch (e) {
            // No specified type, handles all
          }
        });
      }

      ctx.dispatch(ClassListActionCreator.listResult(
          items, 100, GlobalState.firstPageIndex));
    } else {
      Util.alertFail(result, ctx.context);
    }
  }
}

List<DropdownMenuItem> _gradeItemList() {
  final List<DropdownMenuItem> items = List();
  GlobalState.grades.forEach((key, value) {
    items.add(DropdownMenuItem(value: key, child: Text(value)));
  });
  items.removeRange(0, 2);
  return items;
}

Future<Map<String, String>> _inputClassInfo(Context<ClassListState> ctx) async {
  String name = '';
  String grade = 'grade3';

  bool ok = await Alert(
      context: ctx.context,
      title: "创建班级",
      content: StatefulBuilder(builder: (context, StateSetter setState) {
        return Column(
          children: <Widget>[
            TextField(
              decoration: InputDecoration(
                labelText: '请填写班级名称',
              ),
              onChanged: (input) => name = input,
            ),
            DropdownButton(
              isExpanded: true,
              hint: Text('请选择年级'),
              value: grade,
              items: _gradeItemList(),
              onChanged: (item) {
                setState(() {
                  grade = item;
                });
              },
            ),
          ],
        );
      }),
      buttons: [
        DialogButton(
          onPressed: () => Navigator.pop(ctx.context, false),
          child: Text(
            "取消",
            style: TextStyle(color: Colors.white, fontSize: 20),
          ),
        ),
        DialogButton(
          color: Colors.blue,
          onPressed: () => Navigator.pop(ctx.context, true),
          child: Text(
            "修改",
            style: TextStyle(color: Colors.white, fontSize: 20),
          ),
        )
      ]).show();

  if (ok == true) {
    if (name.isEmpty) {
      Util.alert('班级名称不能为空', ctx.context);
      return null;
    }

    return {'name': name, 'gradeId': grade, 'memo': ''};
  }

  return null;
}
